//
//  ZBarViewController.m
//  LazyCat
//
//  Created by jike on 16/1/5.
//  Copyright (c) 2016年 zhanshu. All rights reserved.
//

#import "ZBarViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "NJKWebViewProgress.h"
#import "NJKWebViewProgressView.h"

@interface ZBarViewController ()<AVCaptureMetadataOutputObjectsDelegate,UITextFieldDelegate,UIWebViewDelegate,NJKWebViewProgressDelegate>
{
    AVCaptureSession * session;//输入输出的中间桥梁
    UIView *_viewPreview;// 扫描框
    UIImageView *lefdowImg; // 左上边框
    UIImageView *rightdowImg; // 右下边框
    UITextField *txmTextFild; // 输入条形码号
    UILabel *txmLabel; // 条形码lable
    UIImageView *txmImg; // 条形码img
    UILabel *quedingLable; // 确定
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
    
}
@property (strong, nonatomic) UIView *boxView;
@property (strong, nonatomic) CALayer *scanLayer; // 扫描线
//展示layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic, retain) NSString *orderNum; // 订单号
@property (nonatomic,strong) UIWebView *webView; // webview

@end

@implementation ZBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNav:@"编辑快递" doBack:YES];
    [self saomiao];
}
-(void)createWeb {
    // 创建视图
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    self.webView.backgroundColor = BackColor;
    self.webView.delegate = self;
    [self.webView.scrollView setBounces:YES];//边缘弹动效果
    [self.webView.scrollView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    NSString *url = [NSString stringWithFormat:@"%@/LCatBusiness/ExpressEdit.aspx?plat=ios",BaseUrl];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];// 加载请求
    [self.view addSubview:self.webView];
    [self loadMessPart];//加载进度条
}
//加载进度条
- (void)loadMessPart {
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _webView.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    CGFloat progressBarHeight = 2.f;
    CGRect barFrame = CGRectMake(0, 64, ScreenWidth, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    [_progressView setProgress:0];
    [self.view addSubview:_progressView];
}
//进度条
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [_progressView setProgress:1 animated:NO];
}
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress {
    [_progressView setProgress:progress animated:YES];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSLog(@"%@",requestString);
    NSArray *components = [requestString componentsSeparatedByString:@"@"];//提交请求时候分割参数的分隔符
    if (components.count == 2) {
        NSArray *resultArr = [components[1] componentsSeparatedByString:@":"];
        if ([resultArr count] > 1 && [(NSString *)[resultArr objectAtIndex:0] isEqualToString:@"lanmao_ios"]) {
            //过滤请求是否是我们需要的.不需要的请求不进入条件
            NSString *actionStr = [resultArr objectAtIndex:1];
            if ([actionStr isEqualToString:@"scanExpress"]) {
                [self  saomiao];// 调用扫码功能
                return NO;
            }else {
        
            }
        }
    }
    return YES;
}
// 二维码扫描
-(void)saomiao {
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //初始化链接对象
    session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    [session addInput:input];
    [session addOutput:output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    layer.frame=self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    // 二维码框大小
    _viewPreview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    [self.view addSubview:_viewPreview];
    //6.实例化预览图层
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    //7.设置预览图层填充方式
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    //8.设置图层的frame
    [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    //9.将图层添加到预览view的图层上
    [_viewPreview.layer addSublayer:_videoPreviewLayer];
    //10.设置扫描范围
    output.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.5f, 0.8f);
    //10.1.扫描框
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(50,140,ScreenWidth -100,ScreenWidth -100)];
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    [_viewPreview addSubview:_boxView];
    UIImageView *leftopImg = [[UIImageView alloc] initWithFrame:CGRectMake(45, 135, 25, 25)];
    leftopImg.image = [UIImage  imageNamed:@"lefttop.png"];
    [self.view addSubview:leftopImg];
    lefdowImg = [[UIImageView alloc] initWithFrame:CGRectMake(45, ScreenWidth+140 - 120, 25, 25)];
    lefdowImg.image = [UIImage  imageNamed:@"leftdow.png"];
    [self.view addSubview:lefdowImg];
    UIImageView *righttopImg = [[UIImageView alloc] initWithFrame:CGRectMake(50+ScreenWidth-120, 135, 25, 25)];
    righttopImg.image = [UIImage  imageNamed:@"righttop.png"];
    [self.view addSubview:righttopImg];
     rightdowImg = [[UIImageView alloc] initWithFrame:CGRectMake(50+ScreenWidth-120, ScreenWidth+140 - 120, 25, 25)];
    rightdowImg.image = [UIImage  imageNamed:@"rightdow.png"];
    [self.view addSubview:rightdowImg];
    //10.2.扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
    _scanLayer.backgroundColor = [UIColor colorWithRed:255 green:64 blue:0 alpha:1].CGColor;
    [_boxView.layer addSublayer:_scanLayer];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    [timer fire];
    // 返回button
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(15, 30, 12, 21);
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"lALOCzPrgiYW_22_38"] forState:UIControlStateNormal];
    [self.view addSubview:cancelBtn];
    UIButton *cancelBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn2.frame = CGRectMake(5, 20, 60, 40);
    [cancelBtn2 addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn2];
    // 标题lable
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, ScreenWidth, 20)];
    titleLable.textAlignment = NSTextAlignmentCenter;
    titleLable.font = [UIFont boldSystemFontOfSize:20];
    titleLable.textColor = [UIColor whiteColor];
    titleLable.text = @"条形码/二维码";
    [self.view addSubview:titleLable];
    UILabel *totdayMoney = [[UILabel alloc] initWithFrame:CGRectMake(0, 110, ScreenWidth, 20)];
    totdayMoney.textAlignment = NSTextAlignmentCenter;
    totdayMoney.font = [UIFont boldSystemFontOfSize:16];
    totdayMoney.textColor = [UIColor whiteColor];
    totdayMoney.text = @"对准条形码到框内即可扫描";
    [self.view addSubview:totdayMoney];
    // 输入条形码
    UILabel *txm = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth/2 - 80, 120 + ScreenWidth-50, 160, 40)];
    txm.textAlignment = NSTextAlignmentCenter;
    txm.font = [UIFont boldSystemFontOfSize:16];
    txm.textColor = [UIColor whiteColor];
    txm.layer.cornerRadius = 20;
    txm.alpha = 0.6;
    txm.clipsToBounds = YES;
    txm.backgroundColor = [UIColor blackColor];
    txm.text = @"         输入条形码";
    [self.view addSubview:txm];
    UIImageView *txmlogImg = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth/2 - 50, 133 + ScreenWidth-50, 15, 15)];
    txmlogImg.image = [UIImage  imageNamed:@"txm.png"];
    [self.view addSubview:txmlogImg];
    UIButton *btnTxm = [UIButton buttonWithType:UIButtonTypeCustom];
    btnTxm.frame = CGRectMake(ScreenWidth/2 - 80, 120 + ScreenWidth-50, 160, 40);
    btnTxm.backgroundColor = [UIColor clearColor];
    [btnTxm addTarget:self action:@selector(btnTxmAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnTxm];
    // 条形码textField
    txmTextFild = [[UITextField alloc] initWithFrame:CGRectMake(50,140,ScreenWidth -100,50)];
    [self.view addSubview:txmTextFild];
    txmTextFild.delegate = self;
    txmTextFild.clearButtonMode = UITextFieldViewModeAlways;
    txmTextFild.backgroundColor = [UIColor whiteColor];
    txmTextFild.placeholder = @"请输入条形号码";
    txmTextFild.hidden = YES;
    txmTextFild.keyboardType = UIKeyboardTypeNumberPad;
    // 二维码扫描
    txmLabel = [[UILabel alloc] initWithFrame:CGRectMake(30,210,110,40)];
    txmLabel.textAlignment = NSTextAlignmentCenter;
    txmLabel.font = [UIFont boldSystemFontOfSize:16];
    txmLabel.textColor = [UIColor whiteColor];
    txmLabel.layer.cornerRadius = 20;
    txmLabel.alpha = 0.8;
    txmLabel.clipsToBounds = YES;
    txmLabel.backgroundColor = [UIColor blackColor];
    txmLabel.text = @"      切换扫码";
    [self.view addSubview:txmLabel];
    txmLabel.hidden = YES;
     txmImg = [[UIImageView alloc] initWithFrame:CGRectMake(40, 220, 20, 20)];
    txmImg.image = [UIImage  imageNamed:@"erweima.png"];
    txmImg.hidden = YES;
    [self.view addSubview:txmImg];
    txmLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *txmTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showTxmAction)];
    [txmLabel addGestureRecognizer:txmTap];
    // 确定按钮
    quedingLable = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 140,210,110,40)];
    quedingLable.textAlignment = NSTextAlignmentCenter;
    quedingLable.font = [UIFont boldSystemFontOfSize:16];
    quedingLable.textColor = [UIColor whiteColor];
    quedingLable.layer.cornerRadius = 20;
    quedingLable.alpha = 0.8;
    quedingLable.clipsToBounds = YES;
    quedingLable.backgroundColor = [UIColor blackColor];
    quedingLable.text = @"确定";
    [self.view addSubview:quedingLable];
    quedingLable.hidden = YES;
    quedingLable.userInteractionEnabled = YES;
    UITapGestureRecognizer *querenTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(querenAction)];
    [quedingLable addGestureRecognizer:querenTap];
    //开始捕获
    [session startRunning];
}
// 确认按钮
-(void)querenAction {
    [self.view endEditing:YES];
    NSLog(@"%@",txmTextFild.text);
     NSString *str = [NSString stringWithFormat:@"setBillId('%@')",txmTextFild.text];
    [self.delegate sendNum:str];
    [self.navigationController popViewControllerAnimated:YES];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    self.orderNum = txmTextFild.text;
    NSLog(@"%@",self.orderNum);
    if (txmTextFild.text.length > 2) {
        quedingLable.backgroundColor = [UIColor blueColor];
    }else{
       quedingLable.backgroundColor = [UIColor blackColor];
    }
    return YES;
}
-(BOOL)textFieldShouldClear:(UITextField *)textField {
    quedingLable.backgroundColor = [UIColor blackColor];
    return YES;
}
// 返回条形码扫描
-(void)showTxmAction {
    txmTextFild.hidden = YES;
    txmLabel.hidden = YES;
    quedingLable.hidden = YES;
    txmImg.hidden = YES;
     _scanLayer.hidden = NO;
    [UIView animateWithDuration:1 animations:^{
        _boxView.frame = CGRectMake(50,140,ScreenWidth -100,ScreenWidth -100);
        lefdowImg.frame = CGRectMake(45, ScreenWidth+140 - 120, 25, 25);
        rightdowImg.frame = CGRectMake(50+ScreenWidth-120, ScreenWidth+140 - 120, 25, 25);
        [self.view endEditing:YES];
    }];
}
// 跳转手动输入条形码
-(void)btnTxmAction {
    [self  performSelector:@selector(showKongjianAction) withObject:nil afterDelay:1];
    [UIView animateWithDuration:1 animations:^{
        _boxView.frame = CGRectMake(50,140,ScreenWidth -100,50);
        _scanLayer.hidden = YES;
        lefdowImg.frame = CGRectMake(45, 170, 25, 25);
        rightdowImg.frame = CGRectMake(50+ScreenWidth-120, 170, 25, 25);
        [txmTextFild becomeFirstResponder];
    }];
}
-(void)showKongjianAction {
    txmTextFild.hidden = NO;
    txmLabel.hidden = NO;
    quedingLable.hidden = NO;
    txmImg.hidden = NO;
}
// 返回
-(void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}
// 二维码扫描获取数据
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        [session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        //输出扫描字符串
        NSLog(@"%@",metadataObject.stringValue);
        NSString *str = [NSString stringWithFormat:@"setBillId('%@')",metadataObject.stringValue];
        // 传值给js
//        [self.webView stringByEvaluatingJavaScriptFromString:str];
        [self.delegate sendNum:str];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)moveScanLayer:(NSTimer *)timer {
    CGRect frame = _scanLayer.frame;
    if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        frame.origin.y += 5;
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
